package com.googlecode.spruce.web.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.googlecode.spruce.dao.ServiceGroupScheduleDao;
import com.googlecode.spruce.domain.ServiceGroupSchedule;
import com.googlecode.spruce.schedule.ScheduledRemotePluginService;

@Controller
@RequestMapping("/v1/schedule")
public class ServiceGroupScheduleController
{

    @Autowired
    private ServiceGroupScheduleDao hostServiceDao;

    @Autowired
    private ScheduledRemotePluginService scheduler;

    @RequestMapping(value = "/host/{id}", method = RequestMethod.GET)
    public @ResponseBody
    List<ServiceGroupSchedule> getByServiceId(@PathVariable Integer id)
    {
        return hostServiceDao.getAllByServiceID(id);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public @ResponseBody
    Integer create(@RequestBody final ServiceGroupSchedule hostService)
    {
        Assert.notNull(hostService);
        Assert.isTrue(hostService.getHostID() > 0, "Must have a host ID");
        Assert.isTrue(hostService.getServiceGroupID() > 0, "Must have a group service ID");
        Assert.hasLength(hostService.getCron(), "Must supply cron string");

        final Integer id = hostServiceDao.save(hostService);
        hostService.setId(id);

        scheduler.schedule(hostService);

        return id;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody
    List<ServiceGroupSchedule> getAll()
    {
        return hostServiceDao.getAll();
    }

}
